package com.pomelo.base.core.util;

import freemarker.template.Template;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
 * @ClassName: TemplateUtil
 * @Description:
 * @Author: sunxin
 * @Date: 2021/10/16 11:30
 **/
public class TemplateUtil {

    private TemplateUtil() {
    }

    public static String process(String content, Map<String, Object> model) throws Exception {
        if (content == null || content.isEmpty()) {
            return content;
        }
        StringReader sr = new StringReader(content);
        StringWriter sw = new StringWriter();
        try {
            Template template = new Template("default", sr, null);
            template.process(model, sw);
            String str = sw.toString();
            return str;
        } finally {
            IOUtils.closeQuietly(sr);
            IOUtils.closeQuietly(sw);
        }

    }

    public static String parseInputStream(InputStream is, Map<String, Object> model) throws Exception {
        String content = IOUtils.toString(is, "utf-8");
        return process(content, model);
    }
}
